import axios from 'axios'
import type { AxiosInstance, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

// 🔒 PPH核心API服务 - 重要业务逻辑，修改需审批

interface PPHRecord {
  record_date: string;
  line_name: string;
  order_number: string;
  start_time: string;
  end_time: string;
  quantity: number;
  working_people: number;
  offline_staff: number;
  total_people: number;
  abnormal_loss_minutes?: number;
  break_minutes?: number;
  changeover_minutes?: number;
  material_code: string;
  product_name: string;
  abnormality_category?: string;
  abnormality_description?: string;
}

interface PPHTarget {
  material_code: string;
  line_name: string;
  target_pph: number;
  is_whole_machine: boolean;
  effective_date: string;
}

class PPHService {
  private readonly api: AxiosInstance;
  private baseURL: string;

  /**
   * 智能检测API基础地址
   * 根据当前前端访问地址自动选择对应的后端地址
   * 统一使用3011端口
   */
  private getApiBaseUrl(): string {
    // 优先使用环境变量
    if (import.meta.env.VITE_API_BASE_URL) {
      return import.meta.env.VITE_API_BASE_URL;
    }

    // 获取当前前端访问的主机地址
    const currentHost = window.location.hostname;
    const currentPort = window.location.port;

    console.log(`🌐 前端完整地址: ${window.location.href}`);
    console.log(`🔍 检测主机名: "${currentHost}" (类型: ${typeof currentHost})`);
    console.log(`🔍 检测端口: "${currentPort}"`);
    console.log(`🔍 检测协议: "${window.location.protocol}"`);
    console.log(`🔍 用户代理: ${navigator.userAgent}`);

    // 🚀 智能网络检测 - 自动适应IP地址变化
    let backendUrl: string;
    let networkType: string;

    if (currentHost === 'localhost' || currentHost === '127.0.0.1') {
      backendUrl = 'http://127.0.0.1:3011/api';
      networkType = '本地回环';
      console.log('📡 使用本地后端地址: 127.0.0.1:3011');
    } else if (currentHost.startsWith('192.168.')) {
      backendUrl = `http://${currentHost}:3011/api`;
      networkType = '内网C类';
      console.log(`📡 检测到内网地址: ${currentHost}，使用标准端口3011`);
    } else if (currentHost.startsWith('10.')) {
      backendUrl = `http://${currentHost}:3011/api`;
      networkType = '内网A类';
      console.log(`📡 检测到内网A类地址: ${currentHost}`);
    } else if (currentHost.startsWith('172.')) {
      backendUrl = `http://${currentHost}:3011/api`;
      networkType = '内网B类';
      console.log(`📡 检测到内网B类地址: ${currentHost}`);
    } else {
      backendUrl = `http://${currentHost}:3011/api`;
      networkType = '公网或其他';
      console.log(`📡 使用其他网络地址: ${currentHost}`);
    }

    console.log(`🔗 网络连接配置:`);
    console.log(`   前端地址: ${window.location.protocol}//${currentHost}:${currentPort}`);
    console.log(`   后端地址: ${backendUrl}`);
    console.log(`   网络类型: ${networkType}`);
    console.log(`   时间戳: ${new Date().toISOString()}`);

    return backendUrl;
  }

  constructor() {
    // 🔒 生产环境后端地址 - 智能检测网络环境
    this.baseURL = this.getApiBaseUrl();

    this.api = axios.create({
      baseURL: this.baseURL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    this.setupInterceptors();

    // 启动时测试连接
    this.testConnection();
  }

  /**
   * 获取API基础地址（不包含/api后缀，用于直接访问后端服务）
   */
  getApiUrl(): string {
    // 移除/api后缀，返回纯后端服务地址
    return this.baseURL.replace('/api', '');
  }

  /**
   * 测试API连接
   */
  async testConnection(): Promise<boolean> {
    try {
      console.log(`🔍 测试API连接: ${this.baseURL}`);
      const response = await this.api.get('/health', { timeout: 5000 });
      if (response.status === 200) {
        console.log('✅ API连接测试成功');
        return true;
      } else {
        console.warn(`⚠️ API连接测试失败，状态码: ${response.status}`);
        return false;
      }
    } catch (error: any) {
      console.error('❌ API连接失败:', error.message);
      console.error('🔧 请检查:');
      console.error('  1. 后端服务是否启动 (端口3011)');
      console.error('  2. 网络连接是否正常');
      console.error('  3. 防火墙是否阻止访问');
      console.error(`  4. 后端地址是否正确: ${this.baseURL}`);
      return false;
    }
  }

  private setupInterceptors(): void {
    // 请求拦截器 - 增强日志
    this.api.interceptors.request.use(
      (config) => {
        const timestamp = new Date().toISOString();
        const method = config.method?.toUpperCase() || 'GET';
        const url = config.url || '';
        const fullUrl = config.baseURL + url;

        console.log(`🚀 [${timestamp}] API请求开始:`);
        console.log(`   方法: ${method}`);
        console.log(`   路径: ${url}`);
        console.log(`   完整URL: ${fullUrl}`);
        console.log(`   超时设置: ${config.timeout}ms`);
        console.log(`   请求头:`, config.headers);

        if (config.data) {
          console.log(`   请求数据:`, config.data);
        }

        return config;
      },
      (error) => {
        console.error('❌ 请求配置错误:', error);
        console.error('   错误类型:', error.constructor.name);
        console.error('   错误消息:', error.message);
        const reason = error instanceof Error ? error : new Error(String(error))
        return Promise.reject(reason);
      }
    );

    // 响应拦截器 - 增强日志
    this.api.interceptors.response.use(
      (response: AxiosResponse) => {
        const timestamp = new Date().toISOString();
        const method = response.config.method?.toUpperCase() || 'GET';
        const url = response.config.url || '';
        const status = response.status;
        // 某些 Axios 类型定义不包含 metadata，自定义扩展时可能不存在
        const meta: any = (response.config as any).metadata;
        const duration = meta?.startTime ? Date.now() - meta.startTime : 'unknown';

        console.log(`✅ [${timestamp}] API响应成功:`);
        console.log(`   方法: ${method}`);
        console.log(`   路径: ${url}`);
        console.log(`   状态码: ${status}`);
        console.log(`   响应时间: ${duration}ms`);
        console.log(`   响应大小: ${JSON.stringify(response.data).length} bytes`);

        return response;
      },
      (error) => {
        const timestamp = new Date().toISOString();
        const method = error.config?.method?.toUpperCase() || 'UNKNOWN';
        const url = error.config?.url || 'UNKNOWN';
        const fullUrl = error.config?.baseURL + url;

        console.error(`❌ [${timestamp}] API响应失败:`);
        console.error(`   方法: ${method}`);
        console.error(`   路径: ${url}`);
        console.error(`   完整URL: ${fullUrl}`);
        console.error(`   错误类型: ${error.constructor.name}`);
        console.error(`   错误代码: ${error.code || 'UNKNOWN'}`);

        // 详细的网络错误分析
        if (!error.response) {
          console.error(`🔍 网络连接分析:`);
          console.error(`   - 无响应对象，可能是网络连接问题`);
          console.error(`   - 检查后端服务是否运行在: ${fullUrl}`);
          console.error(`   - 检查防火墙是否阻止端口访问`);
          console.error(`   - 检查网络连通性`);

          if (error.code === 'ECONNREFUSED') {
            console.error(`   - 连接被拒绝，后端服务可能未启动`);
          } else if (error.code === 'ETIMEDOUT') {
            console.error(`   - 连接超时，网络可能有问题`);
          } else if (error.code === 'ENOTFOUND') {
            console.error(`   - 主机未找到，DNS解析可能有问题`);
          }

          ElMessage.error('网络连接失败，请检查网络或后端服务');
          window.dispatchEvent(new CustomEvent('network-error'));
        } else {
          console.error(`   状态码: ${error.response.status}`);
          console.error(`   响应数据:`, error.response.data);
          const message = error.response.data?.message || '服务器错误';
          ElMessage.error(message);
        }

        // 保留原始错误对象，包含 response/status 供调用方判断
        const err = error instanceof Error ? error : Object.assign(new Error(String(error?.message || 'RequestError')), {
          response: error?.response,
          config: error?.config,
          status: error?.status,
          code: error?.code
        });
        return Promise.reject(err);
      }
    );
  }

  // 健康检查
  async healthCheck(): Promise<boolean> {
    try {
  const response = await this.api.get('/health');
  // 后端返回形如 { success, timestamp, data: { status: 'healthy', ... } }
  const status = response?.data?.data?.status || response?.data?.status;
  return status === 'healthy';
    } catch {
      return false;
    }
  }

  // 获取PPH目标值
  async getPPHTarget(materialCode: string, lineName: string, date: string): Promise<number | null> {
    try {
      const response = await this.api.get(`/targets/${materialCode}/${lineName}`, {
        params: { date }
      });
      return response.data.target_pph;
    } catch (error) {
      console.error('获取PPH目标值失败:', error);
      return null;
    }
  }

  // 获取PPH预估值
  async getPPHEstimate(materialCode: string): Promise<number | null> {
    try {
      const response = await this.api.get(`/targets/estimate/${materialCode}`);
      return response.data.estimate_pph;
    } catch (error) {
      console.error('获取PPH预估值失败:', error);
      return null;
    }
  }

  // 保存PPH记录
  async savePPHRecord(record: PPHRecord): Promise<any> {
    try {
      const response = await this.api.post('/records', record);
      ElMessage.success('PPH记录保存成功');
      return response.data;
    } catch (error) {
      console.error('保存PPH记录失败:', error);
      throw error;
    }
  }

  // 获取产品信息
  async getProductInfo(orderNumber: string): Promise<any> {
    try {
      const response = await this.api.get(`/products/order/${orderNumber}`);
      return response.data;
    } catch (error) {
      console.error('获取产品信息失败:', error);
      return null;
    }
  }

  // 获取生产线列表
  async getLines(): Promise<any> {
    try {
      const response = await this.api.get('/products/lines/all');
      // 处理后端返回的数据结构
      if (response.data.success && response.data.data) {
        return response.data.data; // 返回 { lines: [...], count: ... }
      } else {
        return response.data; // 兼容旧格式
      }
    } catch (error) {
      console.error('获取生产线列表失败:', error);
      return { lines: [] };
    }
  }

  // 创建生产线
  async createLine(lineData: any): Promise<any> {
    try {
      const response = await this.api.post('/lines', lineData);
      return response.data;
    } catch (error) {
      console.error('创建生产线失败:', error);
      throw error;
    }
  }

  // 更新生产线状态
  async updateLineStatus(lineId: number, status: string): Promise<any> {
    try {
      const response = await this.api.put(`/lines/${lineId}/status`, { status });
      return response.data;
    } catch (error) {
      console.error('更新生产线状态失败:', error);
      throw error;
    }
  }

  // 删除生产线
  async deleteLine(lineId: number): Promise<any> {
    try {
      const response = await this.api.delete(`/lines/${lineId}`);
      return response.data;
    } catch (error) {
      console.error('删除生产线失败:', error);
      throw error;
    }
  }

  // 获取异常类别列表
  async getAbnormalityCategories(): Promise<any> {
    try {
      const response = await this.api.get('/abnormality-categories');
      // 适配新的API响应格式
      if (response.data.success && response.data.data) {
        return response.data.data; // 返回 { categories: [...] }
      } else {
        return response.data; // 兼容旧格式
      }
    } catch (error) {
      console.error('获取异常类别列表失败:', error);
      return { categories: [] };
    }
  }

  // 创建异常类别
  async createAbnormalityCategory(categoryData: any): Promise<any> {
    try {
      const response = await this.api.post('/abnormality-categories', categoryData);
      return response.data;
    } catch (error) {
      console.error('创建异常类别失败:', error);
      throw error;
    }
  }

  // 删除异常类别
  async deleteAbnormalityCategory(categoryId: number): Promise<any> {
    try {
      const response = await this.api.delete(`/abnormality-categories/${categoryId}`);
      return response.data;
    } catch (error) {
      console.error('删除异常类别失败:', error);
      throw error;
    }
  }

  // 搜索订单 (通过用友API)
  async searchOrders(query: string): Promise<any> {
    try {
      const response = await this.api.get(`/orders/search`, { params: { q: query } });
      const outer = response.data ?? {};
      // 统一解包，兼容 {success,data} 或直接 {orders: []} 或数组
      let payload: any = outer;
      if (outer && typeof outer === 'object' && 'success' in outer && 'data' in outer) {
        payload = outer.data;
      }

      let orders: any[] = [];
      if (Array.isArray(payload)) {
        orders = payload;
      } else if (Array.isArray(payload?.orders)) {
        orders = payload.orders;
      } else if (Array.isArray(payload?.data?.orders)) {
        orders = payload.data.orders;
      } else if (Array.isArray(payload?.items)) {
        orders = payload.items;
      }

      return { orders };
    } catch (error) {
      console.error('搜索订单失败:', error);
      return { orders: [] };
    }
  }

  // 获取订单信息 (通过用友API)
  async getOrderInfo(orderNumber: string): Promise<any> {
    try {
      // 加上 refresh=1 与 fallback=1 以绕过缓存并扩大时间窗口，降低404概率
      const response = await this.api.get(`/orders/${orderNumber}`, { params: { refresh: 1, fallback: 1 } });
      const outer = response.data || {};
      let success = !!outer.success;
      let payload = outer.data;

      if (payload && typeof payload === 'object' && 'success' in payload && 'data' in payload) {
        success = Boolean(payload.success);
        payload = payload.data;
      }

      return { success, data: payload };
    } catch (error) {
      console.error('获取订单信息失败:', error);
      throw error;
    }
  }

  // 获取PPH目标值列表 (用于目标值管理页面)
  async getTargets(params?: any): Promise<any> {
    try {
      const response = await this.api.get('/targets', { params });
      const outer = response.data || {};
      // 兼容后端全局响应包装: { success, data: [...] }
      if (outer && typeof outer === 'object' && 'data' in outer) {
        return outer.data;
      }
      // 旧格式或直返数组
      return outer;
    } catch (error) {
      console.error('获取目标值列表失败:', error);
      return [];
    }
  }

  // 创建PPH目标值
  async createTarget(targetData: any): Promise<any> {
    try {
      const response = await this.api.post('/targets', targetData);
      return response.data;
    } catch (error) {
      console.error('创建目标值失败:', error);
      throw error;
    }
  }

  // 删除PPH目标值
  async deleteTarget(targetId: number): Promise<any> {
    try {
      const response = await this.api.delete(`/targets/${targetId}`);
      return response.data;
    } catch (error) {
      console.error('删除目标值失败:', error);
      throw error;
    }
  }

  // 更新PPH目标值（行内编辑）
  async updateTarget(targetId: number, patch: any): Promise<any> {
    try {
      const response = await this.api.put(`/targets/${targetId}`, patch);
      return response.data;
    } catch (error) {
      console.error('更新目标值失败:', error);
      throw error;
    }
  }

  // 获取PPH目标值 (用于PPH计算)
  async getPPHTargets(params: any): Promise<any> {
    try {
      const response = await this.api.get('/targets/pph', { params });
      const outer = response.data || {};
      // 兼容后端全局响应包装: { success, timestamp?, data: { target_pph, estimate_pph, ... } }
      if (outer && typeof outer === 'object' && 'data' in outer) {
        return outer.data;
      }
      return outer;
    } catch (error) {
      console.error('获取PPH目标值失败:', error);
      return { target_pph: null, estimate_pph: null };
    }
  }

  // 获取PPH记录列表
  async getPPHRecords(params: any = {}): Promise<any> {
    try {
      const response = await this.api.get('/records', { params });
      return response.data;
    } catch (error) {
      console.error('获取PPH记录列表失败:', error);
      throw error;
    }
  }

  // 获取记录列表 (别名方法，用于记录维护页面)
  async getRecords(params: any = {}): Promise<any> {
    return this.getPPHRecords(params);
  }

  // 更新PPH记录
  async updateRecord(id: number, data: any): Promise<any> {
    try {
      const response = await this.api.put(`/records/${id}`, data);
      return response.data;
    } catch (error) {
      console.error('更新PPH记录失败:', error);
      throw error;
    }
  }

  // 删除PPH记录
  async deleteRecord(id: number): Promise<any> {
    try {
      const response = await this.api.delete(`/records/${id}`);
      return response.data;
    } catch (error) {
      console.error('删除PPH记录失败:', error);
      throw error;
    }
  }

  // 创建PPH记录
  async createPPHRecord(data: any): Promise<any> {
    try {
      const response = await this.api.post('/records', data);
      return { success: true, data: response.data };
    } catch (error: any) {
      console.error('创建PPH记录失败:', error);
      const errorMessage = error.response?.data?.error || error.message || '保存失败';
      throw new Error(errorMessage);
    }
  }

  // 批量同步离线记录
  async syncOfflineRecords(records: PPHRecord[]): Promise<any> {
    try {
      const response = await this.api.post('/records/sync', { records });
      ElMessage.success(`成功同步 ${response.data.synced} 条记录`);
      return response.data;
    } catch (error) {
      console.error('同步离线记录失败:', error);
      throw error;
    }
  }

  // 创建PPH目标值
  async createPPHTarget(target: PPHTarget): Promise<any> {
    try {
      const response = await this.api.post('/targets', target);
      ElMessage.success('PPH目标值保存成功');
      return response.data;
    } catch (error) {
      console.error('保存PPH目标值失败:', error);
      throw error;
    }
  }
  // 启动重算异步任务（分批）
  async startRecomputeJob(payload: any): Promise<any> {
    try {
      const res = await this.api.post('/recompute/jobs/start', payload)
      return res.data
    } catch (error) {
      console.error('启动重算任务失败:', error)
      throw error
    }
  }

  // 查询重算任务状态
  async getRecomputeJob(jobId: string): Promise<any> {
    try {
      const res = await this.api.get(`/recompute/jobs/${jobId}`)
      return res.data
    } catch (error) {
      console.error('查询重算任务失败:', error)
      throw error
    }
  }

  // 最近重算任务列表
  getRecomputeJobs = async (limit = 20): Promise<any> => {
    try {
      const res = await this.api.get(`/recompute/jobs`, { params: { limit } })
      return res.data
    } catch (error) {
      console.error('获取重算任务列表失败:', error)
      throw error
    }
  }


  // 取消重算任务
  async cancelRecomputeJob(jobId: string): Promise<any> {
    try {
      const res = await this.api.post(`/recompute/jobs/${jobId}/cancel`)
      return res.data
    } catch (error) {
      console.error('取消重算任务失败:', error)
      throw error
    }
  }

  // 获取PPH汇总数据
  async getPPHSummary(params: any): Promise<any> {
    try {
      const res = await this.api.get('/reports/pph-summary', { params })
      return res.data
    } catch (error) {
      console.error('获取PPH汇总数据失败:', error)
      throw error
    }
  }

  // 获取异常汇总数据
  async getAbnormalSummary(params: any): Promise<any> {
    try {
      const res = await this.api.get('/reports/abnormal-summary', { params })
      return res.data
    } catch (error) {
      console.error('获取异常汇总数据失败:', error)
      throw error
    }
  }

  // 获取异常汇总（周）数据
  async getAbnormalWeeklySummary(params: any): Promise<any> {
    try {
      const res = await this.api.get('/reports/abnormal-weekly', { params })
      return res.data
    } catch (error) {
      console.error('获取异常周汇总数据失败:', error)
      throw error
    }
  }

  // 获取达标率分析数据
  async getEfficiencyAnalysis(params: any): Promise<any> {
    try {
      const res = await this.api.get('/reports/efficiency-analysis', { params })
      return res.data
    } catch (error) {
      console.error('获取达标率分析数据失败:', error)
      throw error
    }
  }

}

// 导出单例实例
export const pphService = new PPHService();
export default pphService;
